import { Avatar, Button, Checkbox, List, Popup } from "antd-mobile";
import styles from "./index.module.css";
import { useState } from "react";

interface PouopItem {
  data: any[];
  setData: any;
  value: boolean;
  setValue: (value: boolean) => void;
  type: "checkbox" | "radio";
}
const Pouops = ({ data,setData, value, setValue, type }: PouopItem) => {
  const handleSub = () => {
    setValue(false);
  };

  const copyJson = (val: any) => {
    return JSON.parse(JSON.stringify(val));
  };

  return (
    <Popup
      visible={value}
      onMaskClick={() => {
        setValue(false);
      }}
      onClose={() => {
        setValue(false);
      }}
      bodyStyle={{ height: "70vh", borderRadius: "12px 12px 0px 0px" }}
    >
      <div className={styles.shopName}>
        <div className={styles.shopName_top}>
          已选（{data.filter((item) => item.checked).length}）
        </div>
        <div className={styles.shopName_center}>
          <List>
            {data.map((item) => {
              return (
                <List.Item>
                  <div className={styles.list_item}>
                    <div className={styles.item_top}>
                      <Avatar
                        src={item?.img || ""}
                        style={{ "--size": "48px", borderRadius: "50%" }}
                      />
                      <span>{item?.name || '-'}</span>
                    </div>
                    <Checkbox
                      checked={item?.checked}
                      onChange={(val: boolean) => {
                        if (type === "checkbox") {
                          const newData: any[] = copyJson(data);
                          const sub: number = data.findIndex(
                            (v) => v.id === item.id
                          );
                          if (sub > -1) {
                            newData[sub].checked = val;
                          }
                          setData(newData);
                        } else {
                          setData(
                            data.map((v: any) => {
                              return {
                                ...v,
                                checked: v.id === item.id ? val : false,
                              };
                            })
                          );
                        }
                      }}
                    />
                  </div>
                </List.Item>
              );
            })}
          </List>
        </div>
        <div className={styles.shopName_bottom}>
          <Button
            color="primary"
            size="large"
            className={styles.button}
            onClick={() => handleSub()}
          >
            确认
          </Button>
        </div>
      </div>
    </Popup>
  );
};

export default Pouops;
